<template>
  <div>
    <h2 style="margin: 20px 0;">我的购物车</h2>

    <!-- 未登录状态 -->
    <template v-if="!store.user">
      <el-empty description="请先登录查看购物车">
        <template #bottom>
          <el-button type="primary" @click="$router.push('/login')">去登录</el-button>
        </template>
      </el-empty>
    </template>

    <!-- 购物车为空（已登录） -->
    <template v-else-if="store.cart.length === 0">
      <el-empty description="购物车是空的，快去添加商品吧">
        <template #bottom>
          <el-button type="primary" @click="$router.push('/')">去购物</el-button>
        </template>
      </el-empty>
    </template>

    <!-- 购物车有商品 -->
    <template v-else>
      <!-- 全选+清空操作栏 -->
      <div style="display: flex; justify-content: space-between; margin-bottom: 10px;">
        <el-checkbox v-model="isAllChecked" @change="handleAllCheck">全选</el-checkbox>
        <el-button type="text" style="color: #f56c6c;" @click="handleClearCart">清空购物车</el-button>
      </div>

      <el-table
        :data="store.cart"
        border
        style="width: 100%; margin-bottom: 20px;"
        @selection-change="handleSelectionChange"
      >
        <!-- 选择框列 -->
        <el-table-column type="selection" width="55" />

        <!-- 商品名称（含失效提示） -->
        <el-table-column prop="name" label="商品名称" width="300">
          <template #default="scope">
            <div>
              {{ scope.row.name }}
              <el-tag type="danger" size="mini" v-if="scope.row.stock === 0" style="margin-left: 10px;">
                已售罄（已失效）
              </el-tag>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="商品图片" width="100">
          <template #default="scope">
            <img :src="scope.row.image" style="width: 80px; height: 80px; object-fit: cover;" />
          </template>
        </el-table-column>

        <el-table-column prop="price" label="单价" />

        <!-- 数量修改列 -->
        <el-table-column label="数量" width="150">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.quantity"
              :min="1"
              :max="scope.row.stock || 1"
              @change="handleQuantityChange(scope.row)"
              @blur="handleQuantityBlur(scope.row)"
              size="small"
              :disabled="scope.row.stock === 0"
            />
          </template>
        </el-table-column>

        <el-table-column label="小计" width="120">
          <template #default="scope">
            ¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button
              type="text"
              style="color: #f56c6c;"
              @click="handleRemoveItem(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 总计+结算栏 -->
      <div style="display: flex; justify-content: space-between; align-items: center; font-size: 18px;">
        <div>
          已选 {{ selectedCount }} 件商品，总计：
          <span style="color: #f56c6c; font-weight: bold;">¥{{ selectedTotal.toFixed(2) }}</span>
        </div>
        <el-button
          type="primary"
          size="large"
          @click="handleCheckout"
          :disabled="selectedCount === 0"
        >
          结算
        </el-button>
      </div>
    </template>
  </div>
</template>

<script setup>
import { computed, ref, watch, onMounted } from 'vue'
import { useStore } from '../store'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

const store = useStore()
const router = useRouter()
const isAllChecked = ref(false)
const selectedItems = ref([])

// 计算选中商品数量和总价
const selectedCount = computed(() => selectedItems.value.length)
const selectedTotal = computed(() => {
  return selectedItems.value.reduce((sum, item) => sum + (item.price * item.quantity), 0)
})

// 监听购物车变化，同步全选状态
watch(
  () => store.cart.length,
  (newVal) => {
    if (newVal === 0) isAllChecked.value = false
    else isAllChecked.value = selectedItems.value.length === newVal
  }
)

// 页面加载时校验失效商品
onMounted(() => {
  checkInvalidItems()
})

// 全选/反选逻辑
const handleAllCheck = (checked) => {
  selectedItems.value = checked ? [...store.cart] : []
}

// 单个商品选中/取消
const handleSelectionChange = (val) => {
  selectedItems.value = val
  isAllChecked.value = val.length === store.cart.length
}

// 修改商品数量
const handleQuantityChange = async (item) => {
  await store.updateCartQuantity(item.id, item.quantity)
  ElMessage.success('数量已更新')
}

// 数量输入框失焦校验
const handleQuantityBlur = async (item) => {
  if (item.stock === 0) return
  if (item.quantity > item.stock) {
    item.quantity = item.stock
    await store.updateCartQuantity(item.id, item.stock)
    ElMessage.warning(`库存不足，已自动调整为最大库存${item.stock}件`)
  } else if (item.quantity < 1) {
    item.quantity = 1
    await store.updateCartQuantity(item.id, 1)
  }
}

// 单个商品删除
const handleRemoveItem = async (id) => {
  await store.removeFromCart(id)
  selectedItems.value = selectedItems.value.filter(item => item.id !== id)
  ElMessage.success('商品已从购物车移除')
}

// 清空购物车
const handleClearCart = async () => {
  await ElMessageBox.confirm('确定要清空购物车吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  for (const item of store.cart) {
    await store.removeFromCart(item.id)
  }
  selectedItems.value = []
  ElMessage.success('购物车已清空')
}

// 结算逻辑
const handleCheckout = () => {
  // 过滤已失效商品
  const validItems = selectedItems.value.filter(item => item.stock > 0)
  if (validItems.length === 0) {
    ElMessage.warning('选中的商品已全部失效，请重新选择')
    return
  }
  ElMessage.success('即将跳转到订单确认页')
  router.push({
    path: '/checkout',
    query: { selectedItems: JSON.stringify(validItems) }
  })
}

// 校验失效商品
const checkInvalidItems = () => {
  const invalidItems = store.cart.filter(item => item.stock === 0)
  if (invalidItems.length > 0) {
    ElMessage.warning(`有${invalidItems.length}件商品已售罄，已自动失效`)
  }
}
</script>
